﻿using System.IO;
using UnityEditor;
using UnityEngine;

/// <summary>
/// 配置文件自动更新
/// </summary>
public static class ConfigFileAutoUpdate
{
    static string[] tableFileChangedList;

    [InitializeOnLoadMethod]
    private static void Init()
    {
        Debug.Log("123");
        tableFileChangedList = new string[0];
        EditorApplication.update += OnUpdate;
        //FileSystemWatcher简史文件系统的变化，检测文件或文件夹的创建、修改、删除等事件
        var tbWatcher = new FileSystemWatcher(ConstEditor.ExcelPath, "*.xlsx");

        tbWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
        tbWatcher.IncludeSubdirectories = true;
        tbWatcher.EnableRaisingEvents = true;
        var fileChangedCb = new FileSystemEventHandler(OnDataTableChanged);
        var fileRenameCb = new RenamedEventHandler(OnDataTableChanged);
        tbWatcher.Changed += fileChangedCb;
        //tbWatcher.Deleted += fileChangedCb;
        //tbWatcher.Renamed += fileRenameCb;
    }
    static int num = 0;
    private static void OnUpdate()
    {
        if (tableFileChangedList.Length > 0)
        {
            num++;

            foreach (string str in tableFileChangedList)
            {
                Debug.Log("更新文件 = " + str);
                FileChuli(str);
            }
            //FolderToolKit.CoutineCheck(ConstEditor.ExcelPath, FileChuli);

            ArrayUtility.Clear(ref tableFileChangedList);
        }
    }

    //文件处理
    private static void FileChuli(string path)
    {
        Debug.Log(ConstEditor.ExcelPath);
        Debug.Log(ConstEditor.JsonPath);

        string xiangduiPath = path.Replace(ConstEditor.ExcelPath, "");
        xiangduiPath = xiangduiPath.Replace(".xlsx", "");
        string str = path.Substring(ConstEditor.ExcelPath.Length, path.Length - ConstEditor.ExcelPath.Length - 5);

        Debug.Log("这是一个文件 = " + str);
        ExcelToolKit.Excel2JsonFile(ConstEditor.ExcelPath + str + ".xlsx", ConstEditor.JsonPath + str + ".json");
    }

    private static void OnDataTableChanged(object sender, FileSystemEventArgs e)
    {
        var fName = Path.GetFileNameWithoutExtension(e.Name);
        if (!fName.StartsWith("~") && !fName.Contains("temp"))
        {
            ArrayUtility.Add(ref tableFileChangedList, e.FullPath);
        }
    }
}